<template>
  <div>
    <el-button type="primary" size="mini" :disabled="disabled" @click="addRule"
      >添加验证</el-button
    >
    <div class="ruleItem" v-for="(item, index) in value" :key="index">
      <div class="inputContainer">
        <el-input
          size="small"
          placeholder="输入正则表达式"
          v-model="value[index].pattern"
          @input="handleRuleChange(index)"
        />
        <el-input
          size="small"
          placeholder="输入错误提示信息"
          v-model="value[index].message"
        />
      </div>
      <i
        class="el-icon-circle-plus"
        v-if="!value[index].confirmed"
        @click="confirmRule(index)"
      />
      <i class="el-icon-delete-solid" v-else @click="removeRule(index)" />
    </div>
  </div>
</template>

<script>
import { Message } from "element-ui";
import { regExpCheck } from "@/utils/util";
export default {
  name: "FieldRulesInput",
  props: {
    value: {
      type: Array,
      required: true,
    },
    field: {
      type: String,
      required: false,
    },
  },
  data() {
    return {};
  },
  computed: {
    disabled() {
      return this.value.some((item) => !item.confirmed);
    },
  },
  methods: {
    addRule() {
      this.value.push({
        confirmed: false,
        pattern: "",
        message: "",
        trigger: "blur",
      });
    },
    handleRuleChange(index) {
      this.value[index].confirmed = false;
    },
    confirmRule(index) {
      const { pattern } = this.value[index];
      if (regExpCheck(pattern)) {
        this.value[index].confirmed = true;
        // window.formPropsController.addFieldRule(this.field, {
        //   pattern: eval(value),
        //   message,
        //   trigger: "blur",
        // });
      } else {
        Message.error("请输入正则表达式");
      }
    },
    removeRule(index) {
      this.value.splice(index, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
.ruleItem {
  display: flex;
  align-items: center;
  .inputContainer {
    padding: 8px 12px;
    background: #f7f7f7;
    border-radius: 4px;
    margin-bottom: 8px;
  }
  i {
    cursor: pointer;
    margin-left: 8px;
  }
}
</style>